package dao.impl;

import hibernate.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import dao.FacturaDAO;
import dominio.Factura;

public class FacturaDAOImpl implements FacturaDAO {
	
	private static FacturaDAOImpl instancia = null;
	
	private static SessionFactory sf = null;

	private FacturaDAOImpl(){}
	
	public static FacturaDAOImpl getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new FacturaDAOImpl();
		} 
		return instancia;
	}
	@Override
	public void grabarFactura(Factura factura) {
		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(factura);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public Factura findUltimaGuardada() {
		Factura factura;
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx= session.beginTransaction();
		factura = (Factura) session.createQuery(
				"select f from Factura f where f.fecha >= all(select f2.fecha from Factura f2)").list().get(0);
		tx.commit();
		session.close();
		return factura;
	}

}
